package oop.controller.action.mark;

import java.util.HashMap;
import java.util.Map;

import oop.controller.action.DefaultAction;
import oop.data.Mark;
import oop.data.Test;
import oop.data.TestVersion;
import oop.db.dao.MarkChoiceDAO;
import oop.db.dao.MarkDAO;
import oop.taglib.UtilFunctions;

public class EditChoicesAction extends DefaultAction {
	private TestVersion version;
	private Mark mark;

	@Override
	public void performImpl() throws Exception {
		long markId = Long.parseLong(request.getParameter("mi_mark"));
		mark = MarkDAO.fetchById(markId);
		version = mark.getTestVersion();
		title("Sửa bài làm của sinh viên " + UtilFunctions.shortStudentInfo(mark));

		String submit = request.getParameter("mi_submit");
		if ("save".equals(submit)) {
			Map<Long, long[]> choices = new HashMap<Long, long[]>();
			MarkChoiceDAO.dropChoices(markId);
			for (Object obj : request.getParameterMap().keySet()) {
				String name = (String) obj;
				if (name.startsWith("mi_q")) {
					long questionId = Long.parseLong(name.substring(4));
					long[] answerIds = new long[request
							.getParameterValues(name).length];
					for (int i = 0; i < answerIds.length; i++) {
						long answerId = Long.parseLong(request
								.getParameterValues(name)[i]);
						answerIds[i] = answerId;
						MarkChoiceDAO.addChoice(markId, questionId, answerId);
					}
					choices.put(questionId, answerIds);
				}
			}

			mark.setMark(UtilFunctions.getMark(version.getTest(), choices));
			MarkDAO.persist(mark);

			if ("create".equals(request.getParameter("mode"))) {
				if ("more".equals(request.getParameter("more"))) {
					setNextAction("mark.create&mc_exam="
							+ mark.getExamination().getId());
				} else {
					setNextAction("exam.view&ev_id="
							+ mark.getExamination().getId());
				}
			} else {
				setNextAction("mark.view&mv_id=" + mark.getId());
			}
		}
	}

	public Mark getMark() {
		return mark;
	}

	public TestVersion getVersion() {
		return version;
	}

	public Test getTest() {
		return version.getTest();
	}

}
